package com.guohengspace.mq.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class IPAddressRangeParser {
    public static void main(String[] args) {
        String ipAddress = "192.168.0.1-192.168.0.10";
        try {
            List ipList = ipRangeParse(ipAddress);
            for (int i = 0; i < ipList.size(); i++) {
                System.out.println(ipList.get(i));
            }
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("1111111111111:" + e.getMessage());
        }
    }

    /**
     * IP地址范围解析
     * @param ipAddress
     * @throws Exception
     */
    public static List ipRangeParse(String ipAddress) throws Exception {
        List<String> ipList = new ArrayList<>();
        if (!ipAddress.contains("-")) {
            throw new Exception("ip范围输入格式不正确");
        }

        if (!hasUniqueCharacters(ipAddress)) {
            throw new Exception("ip范围输入格式不正确，输入了多个-");
        }
        String[] ipRange = ipAddress.split("-");
        String startIP = ipRange[0];
        String endIP = ipRange[1];

        try {
            InetAddress start = InetAddress.getByName(startIP);
            InetAddress end = InetAddress.getByName(endIP);

            byte[] startBytes = start.getAddress();
            byte[] endBytes = end.getAddress();

            long startIPNum = bytesToLong(startBytes);
            long endIPNum = bytesToLong(endBytes);

            for (long ipNum = startIPNum; ipNum <= endIPNum; ipNum++) {
                //System.out.println(longToIP(ipNum));
                ipList.add(longToIP(ipNum));
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return ipList;
    }

    /**
     * 多个 - 符号验证
     * @param str
     * @return
     */
    private static boolean hasUniqueCharacters(String str) {
        // 将字符串转换为字符数组
        char[] charArray = str.toCharArray();
        // 使用Set集合来检查是否有重复字符
        Set<Character> charSet = new HashSet<>();
        for (char c : charArray) {
            if (c == '-') {
                if (!charSet.add(c)) { // 如果添加失败，说明Set中已有该字符
                    return false;
                }
            }
        }
        return true; // 如果所有字符都添加成功，说明都是唯一的
    }

    private static long bytesToLong(byte[] ipAddress) {
        long ipNum = 0;

        for (byte b : ipAddress) {
            ipNum <<= 8;
            ipNum |= (b & 0xFF);
        }

        return ipNum;
    }

    private static String longToIP(long ipNum) {
        StringBuilder ipAddress = new StringBuilder();

        for (int i = 3; i >= 0; i--) {
            ipAddress.append(ipNum >> (8 * i) & 0xFF);
            if (i > 0) {
                ipAddress.append(".");
            }
        }

        return ipAddress.toString();
    }
}
